package cn.tuling.controller;

import cn.tuling.entity.DO.Order;
import cn.tuling.entity.DO.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/order")
@RefreshScope
public class TestController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${isNewBusi}")
    private Boolean isNewBusi;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/services")
    public List<ServiceInstance> getServiceList() {
        List<ServiceInstance> instances = discoveryClient.getInstances("order-service");
        return instances;
    }

    @GetMapping("/newBusiness")
    public String getNewBusiness() {
        if (isNewBusi) {
            return "执行新业务";
        }

        return "执行旧业务";
    }

    @GetMapping("/{orderId}")
    public Order getProduct(@PathVariable Integer orderId) {

        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        if (CollectionUtils.isEmpty(instances)) {
            return null;
        }

        URI productUri = instances.get(0).getUri();
        String requestUri = productUri + "/product/1";

        Product product = restTemplate.getForObject(requestUri, Product.class);
        if (product == null) {
            return null;
        }

        return new Order(orderId, "随便订单", product, "");
    }
}
